import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Permission } from "./entities/permission.entity";
import { DeleteResult, Like, Repository } from "typeorm";

/**
 * @Injectable()：标记该类为一个可注入的服务
 * @InjectRepository(Permission)：注入权限实体的 Repository，用于操作数据库
 * permissionRepository：TypeORM 提供的 Repository 对象，用于执行数据库操作
 */

@Injectable() 
export class PermissionService {
    constructor(
        @InjectRepository(Permission) // 注入权限的实体
        private readonly permissionRepository:Repository<Permission> // 针对于上一行Permission数据库实体的实例
    ){}
    // 查询某个权限的信息
    findOne(id:number):Promise<Permission | null> {
        return this.permissionRepository.findOneBy({ id })
    }
    // 查询所有权限
    findAll(query):Promise<Permission[]> {
        const where:any = {}
        if(query.key) {
            where.key = Like(`%${query.key}%`)
        }
        return this.permissionRepository.find({
            where: where
        })
    }
    // 创建权限
    create(createPermissionDto):Promise<Permission> {
        return this.permissionRepository.save(createPermissionDto)
    }
    // 更新权限
    update(permission) {
        if(permission.id) {
            return this.permissionRepository.update(permission.id, permission)
        }
    }
    // 删除权限
    async delete(permissionId:string):Promise<DeleteResult> {
        // 删除1：删除角色和权限中间表的表相关联的权限
        const delSQL = `delete from role_permission where permissionId = ${permissionId}`
        await this.permissionRepository.query(delSQL)

        // 删除2：删除该权限表的该权限
        return this.permissionRepository.delete(permissionId)
    }
    // 根据用户登录的角色获取到匹配的操作权限
    async getListByRoleName (roles) {
        // 根据角色名称查角色的id
        roles = roles.map((item ) => `'${item}'`)
        const getRoleIdsSQL = `select id from role where name in (${roles.join(',')})` 
        const roldIdRes = await this.permissionRepository.query(getRoleIdsSQL)
        // console.log('roldIdRes', roldIdRes);
        // 根据角色id查询与权限的管理表
        const getRolePermissionSQL = `select permissionId from role_permission where roleId in (${roldIdRes.map((item) => item.id).join(',')})`
        let permissionIdRes = await this.permissionRepository.query(getRolePermissionSQL)
        // 由于是多角色的权限，可能出现重复，需要去重
        permissionIdRes = Array.from(new Set(permissionIdRes.map((item) => item.permissionId)))
        console.log('permissionIdRes', permissionIdRes);
        // 根据权限ID查询对应的数据
        if(permissionIdRes.length > 0) {
            const getPermissionSQL = `select * from permission where id in (${permissionIdRes.join(',')})`
            return await this.permissionRepository.query(getPermissionSQL)
        } else {
            return Promise.resolve([])
        }
        
    }
}